import 'dart:convert';
import 'package:app/api/api.dart';
import 'package:app/common/abs_view.dart';
import 'package:app/responsive.dart';
import 'package:app/utils/aes_utils.dart';
import 'package:app/utils/http_util.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';

class PageContainer extends StatefulWidget {
  const PageContainer({super.key});
  @override
  State<StatefulWidget> createState() {
    return WindowsPageHomeState();
  }
}

class WindowsPageHomeState extends State<PageContainer> {
  int count = 0;
  List<String> banners = [];
  bool autoPlay = true;
  List<dynamic> functions = [];
  MoblieView? _moblieView;
  PCView? _pcView;
  final HttpUtil _httpUtil = HttpUtil();
  @override
  void initState() {
    Future<String?> result = _httpUtil.get(Apis.getBanner);
    result
        .then(
          (value) {
            setState(() {
              Map<String, dynamic> map = jsonDecode(value!);
              var data = jsonDecode(aesDecrypted(map["data"]));
              banners.clear();
              for (Map<String, dynamic> element in data) {
                banners.add(element['imageUrl']);
              }
            });
          },
        )
        .onError((error, stackTrace) {})
        .catchError((err) {});
    _httpUtil.get(Apis.getModules).then((value) {
      setState(() {
        Map<String, dynamic> map = jsonDecode(value!);
        var data = jsonDecode(aesDecrypted(map["data"]));
        functions.clear();
        for (Map<String, dynamic> element in data) {
          functions.add(element);
        }
      });
    });
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    late Widget view;
    if (Responsive.isMobile(context)) {
      _moblieView ??= MoblieView(this);
      view = _moblieView!.getView(context);
    } else {
      _pcView ??= PCView(this);
      view = _pcView!.getView(context);
    }
    return view;
  }
}

class MoblieView implements AbsView {
  WindowsPageHomeState state;
  MoblieView(this.state);

  @override
  Widget getView(BuildContext context) {
    return EasyRefresh(
        child: ListView(
      shrinkWrap: false,
      children: [
        AspectRatio(
          aspectRatio: 1.618,
          child: Swiper(
            itemCount: state.banners.length,
            autoplay: true,
            autoplayDelay: 3000,
            itemBuilder: (context, index) {
              return Image.network(
                state.banners[index],
                fit: BoxFit.cover,
              );
            },
          ),
        )
      ],
    ));
  }
}

class PCView implements AbsView {
  WindowsPageHomeState state;
  PCView(this.state);
  final _ModuleViewsBuilder _moduleViewBuilder = _ModuleViewsBuilder();
  final _HeaderViewBuilder _headerViewBuilder = _HeaderViewBuilder();
  @override
  Widget getView(BuildContext context) {
    return ListView(
      shrinkWrap: true,
      children: [
        _headerViewBuilder.getHeaderView(context, state),
        _moduleViewBuilder.getView(context, state.functions),
      ],
    );
  }
}

class _HeaderViewBuilder {
  Widget getHeaderView(BuildContext context, WindowsPageHomeState state) {
    return Container(
      height: 247.2,
      padding: const EdgeInsets.fromLTRB(18, 0, 18, 0),
      width: double.infinity,
      child: Flex(direction: Axis.horizontal, children: [
        SizedBox(
          height: 247.2,
          width: 400,
          child: Swiper(
            itemCount: state.banners.length,
            autoplay: true,
            autoplayDelay: 3000,
            itemBuilder: (BuildContext context, int index) {
              return Image.network(
                state.banners[index],
                fit: BoxFit.cover,
              );
            },
          ),
        ),
        Flexible(
          flex: 1,
          child: Container(
            padding: const EdgeInsets.all(12),
            decoration: const BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(0)),
              color: Colors.white,
            ),
            child: Align(
              alignment: Alignment.topLeft,
              child: ListView(
                physics: const NeverScrollableScrollPhysics(),
                shrinkWrap: true,
                children: const [],
              ),
            ),
          ),
        )
      ]),
    );
  }
}

class _ModuleViewsBuilder {
  Widget getView(BuildContext context, List<dynamic> modules) {
    final size = MediaQuery.of(context).size;
    double itemWidth = size.width / _Style.getFunctionCount(context);
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: const BoxDecoration(color: Colors.white),
      child: GridView.builder(
        itemCount: modules.length,
        physics: const NeverScrollableScrollPhysics(),
        shrinkWrap: true,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: _Style.getFunctionCount(context),
            //临界点会抖动，待优化
            childAspectRatio: itemWidth / _Style.getFunctionViewHeigth(size)),
        itemBuilder: (context, index) {
          return getItemView(context, modules[index]);
        },
      ),
    );
  }

  Widget getItemView(BuildContext context, dynamic data) {
    final size = MediaQuery.of(context).size;
    return SizedBox(
      width: double.infinity,
      height: _Style.getFunctionViewHeigth(size),
      child: Stack(
        children: [
          Positioned(
              child: SizedBox(
            width: _Style.getFunctionIconWidth(size),
            child: AspectRatio(
              aspectRatio: 1.618,
              child: Container(
                clipBehavior: Clip.hardEdge,
                decoration: const BoxDecoration(
                  borderRadius: BorderRadius.all(
                    Radius.circular(6),
                  ),
                ),
                child: Image.network(
                  data['appLogo'],
                  fit: BoxFit.cover,
                ),
              ),
            ),
          )),
          Positioned(
              left: _Style.getFunctionIconWidth(size) + 8,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    data['appName'],
                    textAlign: TextAlign.left,
                  ),
                  Text(
                    data['pagePath'],
                    textAlign: TextAlign.left,
                  ),
                ],
              ))
        ],
      ),
    );
  }
}

class _Style {
  static double getFunctionIconWidth(Size layoutSize) {
    double width = 120;
    if (layoutSize.width < 900) {
      width = 150;
    }
    return width;
  }

  static double getFunctionViewHeigth(Size layoutSize) {
    double heigth = 100;
    if (layoutSize.width < 900) {
      heigth = 120;
    }
    return heigth;
  }

  static int getFunctionCount(BuildContext context) {
    final Size size = MediaQuery.of(context).size;
    if (size.width <= 900) {
      return 2;
    }
    if (size.width <= 1280) {
      return 3;
    }
    return 5;
  }
}
